<template>
  <div class="product-management">
    <el-dialog
      v-model="dialogVisible"
      title="商品详情"
      width="70%"
      top="5vh"
    >
      <div v-if="selectedProduct" class="product-detail">
        <el-carousel :interval="4000" height="400px">
          <el-carousel-item 
            v-for="(img, index) in selectedProduct.images.split(',')"
            :key="index"
          >
            <img 
              :src="'http://localhost:8092' + img" 
              class="detail-image"
            />
          </el-carousel-item>
        </el-carousel>

        <div class="detail-info">
          <h2>{{ selectedProduct.productName }}</h2>
          <el-divider />
          
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="info-item">
                <span class="label">价格：</span>
                <span class="value price">¥{{ selectedProduct.price }}</span>
              </div>
              <div class="info-item">
                <span class="label">类型：</span>
                <el-tag 
                  :type="selectedProduct.saleType === 0 ? 'success' : 'warning'"
                  size="medium"
                >
                  {{ selectedProduct.saleType === 0 ? '普通商品' : '竞拍商品' }}
                </el-tag>
              </div>
              <div class="info-item">
                <span class="label">分类：</span>
                <el-tag type="info">{{ selectedProduct.category }}</el-tag>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <span class="label">年级：</span>
                <span class="value">{{ selectedProduct.grade }}</span>
              </div>
              <div class="info-item">
                <span class="label">专业：</span>
                <span class="value">{{ selectedProduct.major }}</span>
              </div>
            </el-col>
          </el-row>

          <el-divider />
          
          <div class="description">
            <h3>商品描述</h3>
            <p>{{ selectedProduct.introduction }}</p>
          </div>
        </div>
      </div>
    </el-dialog>

    <el-card class="search-box">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索商品名称"
            clearable
            @keyup.enter="handleSearch"
          >
            <template #append>
              <el-button @click="handleSearch">
                <el-icon><Search /></el-icon>
              </el-button>
            </template>
          </el-input>
        </el-col>
        <el-col :span="16">
          <el-form :inline="true">
            <el-form-item label="价格范围">
              <el-input-number v-model="filterParams.minPrice" :min="0" />
              <span class="mx-1">-</span>
              <el-input-number v-model="filterParams.maxPrice" :min="0" />
            </el-form-item>
            <el-form-item label="分类">
              <el-select 
                v-model="filterParams.categories"
                multiple
                collapse-tags
                placeholder="选择分类"
              >
                <el-option
                  v-for="item in ['书籍','数码','服饰']"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
            <el-button type="primary" @click="applyFilters">应用筛选</el-button>
          </el-form>
        </el-col>
      </el-row>
    </el-card>

    <el-card class="product-list">
      <el-row :gutter="20">
        <el-col
          v-for="product in products"
          :key="product.productId"
          :xs="24"
          :sm="12"
          :md="8"
          :lg="6"
          class="product-item"
        >
          <el-card shadow="hover">
            <div class="product-header">
              <el-tag 
                :type="product.saleType === 0 ? 'success' : 'warning'"
                class="type-tag"
                effect="dark"
              >
                {{ product.saleType === 0 ? '普通' : '竞拍' }}
              </el-tag>
            </div>
            
            <el-carousel :interval="4000" height="200px">
              <el-carousel-item 
                v-for="(img, index) in product.images.split(',')"
                :key="index"
              >
                <img 
                  :src="'http://localhost:8092' + img" 
                  class="product-image"
                />
              </el-carousel-item>
            </el-carousel>
            
            <div class="product-info">
              <h3 class="product-name">{{ product.productName }}</h3>
              <div class="meta-info">
                <div class="product-price">¥{{ product.price }}</div>
                <el-tag type="info" size="small">{{ product.category }}</el-tag>
              </div>
              <div class="product-actions">
                <el-button 
                  type="primary"
                  @click="viewDetail(product.productId)"
                >
                  查看详情
                </el-button>
                <el-button
                  type="danger"
                  @click="deleteProductByAdmin(product.productId)"
                >
                  删除
                </el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-pagination
        v-model:current-page="pagination.current"
        :page-size="pagination.pageSize"
        :total="pagination.total"
        layout="total, prev, pager, next"
        @current-change="handlePageChange"
      />
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

const dialogVisible = ref(false)
const selectedProduct = ref(null)
const products = ref([])
const searchKeyword = ref('')
const filterParams = ref({
  minPrice: null,
  maxPrice: null,
  categories: []
})

const pagination = ref({
  current: 1,
  pageSize: 12,
  total: 0
})

const fetchProducts = async () => {
  try {
    const params = {
      page: pagination.value.current,
      pageSize: pagination.value.pageSize,
      keyword: searchKeyword.value,
      ...filterParams.value
    }

    const { data } = await axios.get('http://localhost:8092/product/list', { params })
    
    if (data.code === 200) {
      products.value = data.data
      pagination.value.total = data.total || 0
    }
  } catch (error) {
    ElMessage.error('获取商品列表失败')
  }
}

const handleSearch = () => {
  pagination.value.current = 1
  fetchProducts()
}

const applyFilters = () => {
  pagination.value.current = 1
  fetchProducts()
}

const handlePageChange = (page) => {
  pagination.value.current = page
  fetchProducts()
}

const viewDetail = (productId) => {
  axios.get(`http://localhost:8092/product/getDetailBySingleId?productId=${productId}`)
    .then(response => {
      if(response.data.code === 200 && response.data.data.length > 0) {
        selectedProduct.value = response.data.data[0]
        dialogVisible.value = true
      }
    })
    .catch(error => {
      ElMessage.error('获取商品详情失败')
    })
}

const deleteProductByAdmin = async (productId) => {
  try {
    await ElMessageBox.confirm('确认删除该商品？', '删除确认', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const { data } = await axios.delete(
      'http://localhost:8092/product/deleteProductByAdmin',
      {
        params: { productId },
        headers: {
          Authorization: `Bearer ${localStorage.getItem('token')}`
        }
      }
    )

    if (data.code === 200) {
      ElMessage.success('删除成功')
      if (products.value.length === 1 && pagination.value.current > 1) {
        pagination.value.current--
      }
      fetchProducts()
    }
  } catch (error) {
   if (error !== 'close' && error !== 'cancel') {
      ElMessage.error(`删除失败: ${error.response?.data?.msg || error.message}`)
    }
  }
}

const isAdmin = computed(() => {
  const user = JSON.parse(localStorage.getItem('user'))
  return user?.role === '00'
})

onMounted(fetchProducts)
</script>

<style scoped>
.product-management {
  padding: 20px;
}

.search-box {
  margin-bottom: 20px;
}

.product-list {
  margin-top: 20px;
}

.product-item {
  margin-bottom: 20px;
  position: relative;
}

.product-header {
  position: absolute;
  top: 10px;
  right: 10px;
  z-index: 2;
}

.type-tag {
  font-size: 14px;
  padding: 6px 12px;
  border-radius: 4px;
}

.product-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

.product-info {
  padding: 15px;
}

.product-name {
  margin: 10px 0;
  font-size: 16px;
  color: #333;
  height: 40px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.meta-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 15px 0;
}

.product-price {
  color: #f56c6c;
  font-size: 18px;
  font-weight: bold;
}

.product-actions {
  margin-top: 15px;
  display: flex;
  justify-content: space-between;
}

.el-pagination {
  margin-top: 20px;
  justify-content: center;
}

.detail-image {
  width: 100%;
  height: 400px;
  object-fit: contain;
  background: #f5f7fa;
}

.detail-info {
  margin-top: 20px;
}

.info-item {
  margin: 15px 0;
  font-size: 16px;
}

.label {
  color: #909399;
  margin-right: 10px;
}

.value {
  color: #303133;
}

.price {
  color: #f56c6c;
  font-size: 24px;
  font-weight: bold;
}

.description {
  margin-top: 30px;
}
</style>